package com.stx.openeyes.view.fragment;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItem;
import com.stx.openeyes.R;
import com.stx.openeyes.SealConst;
import com.stx.openeyes.adapter.MyVideoItemAdapter;
import com.stx.openeyes.dto.Response;
import com.stx.openeyes.model.HotStraetgyEntity;
import com.stx.openeyes.model.User;
import com.stx.openeyes.model.Video;
import com.stx.openeyes.utils.CommonAdapter;
import com.stx.openeyes.utils.ContextUtil;
import com.stx.openeyes.utils.HttpAdress;
import com.stx.openeyes.utils.NToast;
import com.stx.openeyes.utils.ViewHolder;
import com.stx.openeyes.view.activity.FunctionActivity;
import com.stx.openeyes.view.activity.LoginActivity;
import com.stx.openeyes.view.activity.VideoDetailActivity;
import com.stx.openeyes.widget.LoadDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * 视频分类通用fragment
 */
public class CommonHotFragment extends Fragment {

    private List<Video> itemListEntities = new ArrayList<>();
    @BindView(R.id.hot_listview)
    ListView hotListview;
    protected Context mContext;
    @BindView(R.id.footer_ll)
    LinearLayout linearLayout;
    @BindView(R.id.footer_tv)
    TextView textView;
    private CommonAdapter commonAdapter;
    private boolean first = true;

    //-1 关注；0 推荐
    private static final Integer[] CATEGORY = new Integer[]{
            -1, 0, 1, 2, 3, 4, 5, 6, 7, 8
    };

    public CommonHotFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_common_hot_fragment, container, false);
        //获取控件
        ButterKnife.bind(this, inflate);
        mContext = getActivity();

        initData();
        setListener();

        return inflate;
    }

    // 初始化数据
    private void initData() {
        int position = FragmentPagerItem.getPosition(getArguments());
        Log.i("---->position", position + "");
        Integer stretary = CATEGORY[position];
        String url = String.format(HttpAdress.VIDEOS, stretary);

        OkHttpUtils.get()
                .url(url)
                .addHeader("token", ContextUtil.getCurrentUserToken())
                .addHeader("deviceId", ContextUtil.getDevicedId())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        Log.e("---error", "error msg is :" + e.getMessage());
                        NToast.shortToast(mContext, SealConst.NETWORK_ERROR);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        pareJson(response, stretary);
                    }
                });
    }

    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
        super.handleMessage(msg);
        if (msg.what == 0) {
            hotListview.setVisibility(View.GONE);
            linearLayout.setVisibility(View.VISIBLE);
            textView.setText("-Temporarily No Data-");

            if (msg.arg1 == -1 && msg.arg2 == 4043) { // 用户关注
                textView.setText("-Please Login First-");
                // 增加点击事件
                textView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(mContext, LoginActivity.class));
                    }
                });
            }
        } else {
            hotListview.setVisibility(View.VISIBLE);
            linearLayout.setVisibility(View.GONE);
        }
        }
    };

    // 解析json数据
    private void pareJson(String jsonData, Integer stretary) {
        Response<List<Video>> videoResp = new Gson().fromJson(jsonData, new TypeToken<Response<List<Video>>>() {
        }.getType());
        if (videoResp.isSuccess())
            itemListEntities.addAll(videoResp.getData());
        Message msg = Message.obtain();
        msg.what = itemListEntities.size();
        msg.arg1 = stretary;
        msg.arg2 = videoResp.getCode();
        mHandler.sendMessage(msg);

        if (first) {
            // 设置适配器
            setAdapter(itemListEntities);
        } else {
            if (commonAdapter != null)
                commonAdapter.notifyDataSetChanged();
        }
    }

    public void callResume(int position) {
        itemListEntities.clear();
        initData();
        first = false;
    }

    //设置适配器
    private void setAdapter(final List<Video> dataEntity) {
        commonAdapter = new CommonAdapter<Video>(getContext(), dataEntity, R.layout.list_hot_item) {
            @Override
            public void convert(ViewHolder viewHolder, Video itemListEntity) {
                viewHolder.setText(R.id.tv_title, itemListEntity.getTitle());
                viewHolder.setText(R.id.tv_time, itemListEntity.getDurationStr());
                viewHolder.setText(R.id.tv_tag, itemListEntity.getTagStr());
                ImageView imageView = viewHolder.getView(R.id.iv);
                if (itemListEntity.getType() == 1) {
                    viewHolder.setVisible(R.id.tv_vip, true);
                } else {
                    viewHolder.setVisible(R.id.tv_vip, false);
                }
                Glide.with(mContext).load(itemListEntity.getPreviewImg()).into(imageView);
            }
        };
        hotListview.setAdapter(commonAdapter);
    }

    //设置事件监听
    private void setListener() {
        //listview点击事件
        hotListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getContext(), VideoDetailActivity.class);
                Bundle bundle = new Bundle();
                Log.i("--->", position + "");
                Video data = itemListEntities.get(position);
                bundle.putInt("id", data.getId()); // 视频id
                bundle.putString("title", data.getTitle());
                bundle.putString("time", data.getDurationStr());
                bundle.putString("desc", data.getDescription());//视频描述
                bundle.putString("blurred", data.getPreviewImg());//模糊图片地址
                bundle.putString("feed", data.getPreviewImg());//图片地址
                bundle.putString("video", data.getUrl());//视频播放地址
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

       /* hotListview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                LinearLayout ll_moban = (LinearLayout) v.findViewById(R.id.ll_moban);
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP://手指抬起
                        ll_moban.setVisibility(View.VISIBLE);
                        break;
                    case MotionEvent.ACTION_DOWN://手指按下
                        ll_moban.setVisibility(View.GONE);
                        break;
                    case MotionEvent.ACTION_MOVE://手指离开
                        ll_moban.setVisibility(View.VISIBLE);
                    default:
                        ll_moban.setVisibility(View.VISIBLE);
                        break;
                }
                return false;
            }
        });*/
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}
